package com.aegis.autodeployplugin.tasks;

import com.aegis.autodeployplugin.AutoDeployPlugin;
import com.aegis.autodeployplugin.api.RetrofitUtil;
import com.aegis.autodeployplugin.entity.extension.UploadExtension;
import com.aegis.autodeployplugin.entity.params.DingTalkRequestBody;
import com.aegis.autodeployplugin.entity.params.DingTalkLinkModel;
import com.aegis.autodeployplugin.service.ApiService;

import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * desc     :
 *
 * @author : Aegis_Lee
 * date     : 2021/7/19
 * email    : 476810504@qq.com
 */
public class NotifyTask extends DefaultTask {
    private static DingTalkLinkModel sDingTalkLinkModel;
    private UploadExtension mUploadExtension;

    public void init(UploadExtension extension) {
        this.mUploadExtension = extension;
        setDescription("send message to ding talk");
        setGroup(AutoDeployPlugin.PLUGIN_EXTENSION_NAME);
    }

    /**
     * 设置通知参数
     *
     * @param params {@link DingTalkLinkModel}
     */
    public static void setDingTalkParams(DingTalkLinkModel params){
        sDingTalkLinkModel = params;
    }

    @TaskAction
    public void sendNotifyMessage(){
        try {
            Long timestamp = System.currentTimeMillis();
            Response<ResponseBody> response = RetrofitUtil.getInstance()
                    .create("https://oapi.dingtalk.com")
                    .create(ApiService.class)
                    .sendMessage(mUploadExtension.dingTalkAccessToken, timestamp,
                            RetrofitUtil.getInstance().createSign(timestamp, mUploadExtension.dingTalkSecret),
                            new DingTalkRequestBody(new DingTalkLinkModel(
                                    sDingTalkLinkModel.title,
                                    sDingTalkLinkModel.text,
                                    sDingTalkLinkModel.picUrl,
                                    sDingTalkLinkModel.messageUrl)))
                    .execute();

            // 打印请求结果，方便实际使用时查错
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
